<template>
  <view class="page">
    <div class="container">
      <div class="canvas-box" :class="{ active: activeQR === 1 }">
        <uQrcode ref="uqrcode" :auto="false" canvas-id="qrcode" :value="codeValue1" />
      </div>
      <div class="canvas-box" :class="{ active: activeQR === 2 }">
        <uQrcode ref="uqrcode2" :auto="false" canvas-id="qrcode2" :value="codeValue2" />
      </div>
    </div>
  </view>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import uQrcode from '@/uni_modules/Sansnn-uQRCode/components/u-qrcode/u-qrcode.vue'

const uqrcode = ref()
const uqrcode2 = ref()
const activeQR = ref(1) // 当前显示的二维码(1或2)
const codeValue1 = ref('初始值1') // 第一个二维码的值
const codeValue2 = ref('初始值2') // 第二个二维码的值
const nextValue = ref('') // 存储下一次要切换的值
let timer = null

// 模拟异步获取下一次的二维码值
const fetchNextQRValue = async () => {
  // 这里替换为你的实际获取逻辑
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`新值_${Date.now()}`) // 模拟生成新值
    }, 100)
  })
}

// 刷新指定二维码
const refreshQR = async (qrRef, newValue) => {
  qrRef.value.value = newValue
  await qrRef.value.remake()
}

// 主定时器逻辑
const startTimer = async () => {
  let cycleCount = 0

  const cycle = async () => {
    cycleCount++
    console.log(`第${cycleCount}次循环开始`)

    // 0秒：显示当前二维码
    console.log('显示二维码', activeQR.value)

    // 5秒时预生成下一个二维码值并绘制到非活跃二维码上
    setTimeout(async () => {
      nextValue.value = await fetchNextQRValue()
      console.log('5秒：预生成下次值', nextValue.value)

      // 在非活跃二维码上预绘制
      const inactiveQR = activeQR.value === 1 ? uqrcode2 : uqrcode
      await refreshQR(inactiveQR, nextValue.value)
    }, 5000)

    // 8秒时切换显示预绘制的二维码
    setTimeout(async () => {
      activeQR.value = activeQR.value === 1 ? 2 : 1
      console.log('8秒：切换到二维码', activeQR.value)

      // 开启下一个循环
      cycle()
    }, 8000)
  }

  // 首次启动
  await cycle()
}

onMounted(async () => {
  // 初始绘制两个二维码
  await refreshQR(uqrcode, codeValue1.value)
  await refreshQR(uqrcode2, codeValue2.value)
  startTimer()
})

onUnmounted(() => {
  clearTimeout(timer)
})
</script>

<style lang="scss" scoped>
.container {
  width: 200px;
  height: 200px;
  position: relative;
  .canvas-box {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 0;
    top: 0;
    opacity: 0;
  }
  .active {
    opacity: 1;
  }
}
</style>
